﻿using System.Windows;
using System.Windows.Input;
using System.Collections.Generic;

namespace ManPowerEngine
{
	public class InputSystem
	{
		private static InputSystem msInputSystem;
		private static FrameworkElement msTarget;

		private Dictionary<Key, bool> isPressed = new Dictionary<Key, bool>();

		internal InputSystem(FrameworkElement target)
		{
			msInputSystem = this;
			msTarget = target;

			clearKeyPresses();
			msTarget.KeyDown += new KeyEventHandler(target_KeyDown);
			msTarget.KeyUp += new KeyEventHandler(target_KeyUp);
			msTarget.LostFocus += new RoutedEventHandler(target_LostFocus);
		}

		internal void CleanUp() {
			clearKeyPresses();
			msTarget.KeyDown -= new KeyEventHandler(target_KeyDown);
			msTarget.KeyUp -= new KeyEventHandler(target_KeyUp);
			msTarget.LostFocus -= new RoutedEventHandler(target_LostFocus);
			msTarget = null;
		}

		/// <summary>
		/// get the istance of input system
		/// </summary>
		public static InputSystem Instance
		{
			get { return msInputSystem; }
		}

		public void clearKeyPresses()
		{
			isPressed.Clear();
		}

		void target_KeyDown(object sender, KeyEventArgs e)
		{
			if (!isPressed.ContainsKey(e.Key))
			{
				isPressed.Add(e.Key, true);
			}
		}

		void target_KeyUp(object sender, KeyEventArgs e)
		{
			if (isPressed.ContainsKey(e.Key))
			{
				isPressed.Remove(e.Key);
			}
		}

		void target_LostFocus(object sender, RoutedEventArgs e)
		{
			clearKeyPresses();
		}

		public bool isKeyPressed(Key k)
		{
			return isPressed.ContainsKey(k);
		}
	}
}
